package com.geekai.chat.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.geekai.chat.common.Result;
import com.geekai.chat.dto.ChatRequest;
import com.geekai.chat.dto.ChatResponse;
import com.geekai.chat.dto.ConversationDto;
import com.geekai.chat.entity.Conversation;
import com.geekai.chat.service.AiChatService;
import com.geekai.chat.service.ConversationService;
import com.geekai.chat.service.ModelSelectionService;

import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/chat")
@RequiredArgsConstructor
public class ChatController {

    private final AiChatService aiChatService;
    private final ConversationService conversationService;
    private final ModelSelectionService modelSelectionService;

    /**
     * 获取当前认证用户的用户名
     */
    private String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && !"anonymousUser".equals(authentication.getName())) {
            return authentication.getName();
        }
        throw new RuntimeException("用户未登录");
    }

    @PostMapping("/conversations")
    public Result<Conversation> createConversation(@RequestParam(required = false) String title) {
        try {
            String username = getCurrentUsername();
            Conversation conversation = conversationService.createConversation(username, title);
            return Result.success(conversation);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/conversations")
    public Result<List<ConversationDto>> getConversations() {
        try {
            String username = getCurrentUsername();
            List<ConversationDto> conversations = conversationService.getUserConversations(username);
            return Result.success(conversations);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/conversations/{conversationId}")
    public Result<ConversationDto> getConversation(@PathVariable Long conversationId) {
        try {
            String username = getCurrentUsername();
            ConversationDto conversation = conversationService.getConversationWithMessages(conversationId, username);
            return Result.success(conversation);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @DeleteMapping("/conversations/{conversationId}")
    public Result<Void> deleteConversation(@PathVariable Long conversationId) {
        try {
            String username = getCurrentUsername();
            conversationService.deleteConversation(conversationId, username);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PutMapping("/conversations/{conversationId}/title")
    public Result<Void> updateConversationTitle(@PathVariable Long conversationId, @RequestParam String title) {
        try {
            String username = getCurrentUsername();
            conversationService.updateConversationTitle(conversationId, title, username);
            return Result.success();
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/send")
    public Result<ChatResponse> sendMessage(@Valid @RequestBody ChatRequest chatRequest) {
        try {
            String username = getCurrentUsername();
            ChatResponse response = aiChatService.chat(chatRequest, username);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamMessage(@Valid @RequestBody ChatRequest chatRequest) {
        try {
            String username = getCurrentUsername();
            return aiChatService.streamChat(chatRequest, username);
        } catch (Exception e) {
            SseEmitter emitter = new SseEmitter();
            try {
                emitter.send(SseEmitter.event().data("error: " + e.getMessage()));
                emitter.complete();
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
            return emitter;
        }
    }

    @GetMapping("/models")
    public Result<List<ModelSelectionService.ModelInfo>> getAvailableModels() {
        try {
            List<ModelSelectionService.ModelInfo> models = modelSelectionService.getAvailableModels();
            return Result.success(models);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/generate-title")
    public Result<String> generateTitle(@RequestParam String content) {
        try {
            String title = aiChatService.generateTitle(content);
            return Result.success(title);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}